<template lang="pug">
.upload-section
  .upload-section-header
    .upload-section-title 物料间样品信息
  .upload-section-content
    .form-item.form-item-start
      .form-item-label.form-item-label_import 物料间样品信息：
      .form-item-spec
        draggable(:list="sampleData.items", v-bind="dragOptions" @end="draggableEnd")
          transition-group(type="transition" name="flip-list" tag="div")
            .spec-table(v-for="(item, index) in sampleData.items", :key="`spec_${index}`" v-if="sampleData.items.length")
              .spec-table-header
                .spec-hd-value
                  .spec-hd-value-label 规格名称
                  .spec-hd-value-bd
                    el-input(size="mini" placeholder="请输入规格" maxlength="6" show-word-limit v-model="item.name" @change="changeSpecName(item, index)")
                .spec-hd-handle(@click="delSpec(item, index)")
                  .icon-trash
                  .spec-hd-handle-btn 删除
              .spec-table-body
                .spec-table-body-label 规格值
                draggable.form-item-draggable(:list="item.values", v-bind="dragChildOptions" handle=".spec-item-ft")
                  transition-group.form-item-draggable-transition(type="transition" name="flip-list" tag="div")
                    .spec-table-body-value(v-for="(row, rowIndex) in item.values" :key="rowIndex" v-if="item.name")
                      .spec-table-body-input
                        .iconfont.el-icon-error(@click="delSpecValue(row, rowIndex, item.values)")
                        el-input(v-model="row.name" size="mini" @change="changeSpecValue(item, row, index, rowIndex)")
                      //- .spec-table-body-uploadbtn(v-if="item.showUploadBtn")
                        .spec-table-body-img(v-if="row.image", @click="seeImage(row.image)" :style="row.image | filterUrl")
                          .iconfont.el-icon-error(@click="deleteImage(row, rowIndex)")
                        .spec-table-body-upload(v-else) 上传图片
                          input.el-input(type="file" accept="image/png, image/jpeg, image/jpg" @change="changeFile($event, index, rowIndex)")
                      .spec-item-ft
                        .iconfont.icon-move
                .spec-table-body-ft(@click="addSpec(item)" v-if="item.name") 添加规格值
        .spec-table-handle
          el-button(size="mini" icon="el-icon-plus" plain @click="settingSpec") 添加规格
          .spec-table-handle-info 最多3个
    .form-item.form-item-start.spec-sku(v-if="sampleData.table.body.length")
      .form-item-label.form-item-label_import 规格明细：
      .spec-sku-table
        .spec-sku-info SKU表将根据规格的变化动态生成，请填写价格、库存等信息
        .spec-sku-table-body
          navbar(:navbar="sampleData.table.header")
          .table-list
            .table-tr(v-for="row, rowIndex in sampleData.table.body" :key="`input_${rowIndex}`" v-if="rowIndex === 0")
              .table-td(
                v-for="item, index in row"
                :key="index"
              )
                .table-td-body.table-td-input(v-if="index > (row.length - 3)")
                  el-select(size="mini" placeholder="请选择" v-if="index === (row.length - 2)" @change="changePrice(2, 'unit')" v-model="skuForm.unit")
                    el-option(v-for="item, index in unitList" :key="index" :label="item.label" :value="item.value")
                  el-input(size="mini" placeholder="0" v-if="index === (row.length - 1)" @change="changePrice(1, 'store_count')" v-model="skuForm.store_count")
                .table-td-body(v-else)
              .table-td.table-td-del
            .table-tr(v-for="row, rowIndex in sampleData.table.body" :key="rowIndex")
              .table-td(
                v-for="item,index in row"
                :key="index"
              )
                .table-td-body.table-td-input(v-if="index > (row.length - 3)")
                  el-select(size="mini" v-model="row[index]" placeholder="请选择" v-if="index === (row.length - 2)")
                    el-option(v-for="item, index in unitList" :key="index" :label="item.label" :value="item.value")
                  el-input(size="mini" placeholder="请输入库存" v-model="row[index]" @change="changeCostPrice(item, index, row)" type="number" v-if="index === (row.length - 1)")
                .table-td-body(v-else) {{item}}
              .table-td.table-td-del(@click="deleteSku(row, rowIndex)") 删除
</template>

<script>
import draggable from 'vuedraggable'
import navbar from '@/components/navbar'
export default {
  name: 'sampleSpec',
  props: {
    sampleData: Object
  },
  components: {
    draggable,
    navbar,
  },
  data () {
    return {
      skuForm: {
        unit: '',
        store_count: ''
      },
      unitList: [
        { label: '件', value: '件' },
        { label: '套', value: '套' },
        { label: '块', value: '块' },
        { label: '个', value: '个' },
      ],
    }
  },
  computed: {
    dragOptions () {
      return {
        animation: 60,
        handle: '.spec-table'
      }
    },
    dragChildOptions () {
      return {
        animation: 60,
        handle: '.icon-move'
      }
    }
  },
  methods: {
    // 规格处理
    // 规格调整位置更新SKU表
    draggableEnd (e) {
      this.updataTable()
    },
    // 规格名称修改
    changeSpecName (item, index) {
      if (!item.name) {
        this.sampleData.items[index].values = []
      }
      this.updataTable()
    },
    // 删除规格项
    async delSpec (item, index) {
      this.$confirm('确定删除该规格吗？', '删除规格提示', {
        customClass: 'sold-message_box',
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'sold-button_sure'
      }).then(async () => {
        this.sampleData.items.splice(index, 1)
        this.setUploadBtn()
        this.updataTable()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      })
    },
    // 删除规格属性
    delSpecValue (row, index, arr) {
      arr.splice(index, 1)
      this.updataTable()
    },
    // 规格值改变更新SKU
    changeSpecValue (item, row, index, rowIndex) {
      if (!row.name.replace(/^\s+|\s+$/g,"")) {
        this.$message.error('规格值不可以为空！')
      } else {
        row.is_selected = true
        this.updataTable()
      }
    },
    // 大图预览图片
    seeImage (file) {
      this.changePreviewModal({
        show: true,
        url: file
      })
    },
    // 删除规格属性图片
    deleteImage (row, index) {
      row.image = ''
    },
    // 添加规格属性
    async addSpec (item) {
      try {
        item.values.push({
          image: '',
          is_selected: true,
          name: ''
        })
      } catch ({ msg }) {
        this.$message.error(msg)
      }
    },
    // 添加规格项
    async settingSpec () {
      try {
        if (this.sampleData.items.length >= 3) {
          this.$message.error('材料规格最多3个！')
          return
        }
        this.sampleData.items.push({
          name: '',
          showUploadBtn: false,
          values: []
        })
      } catch ({ msg }) {
        this.$message.error(msg)
      }
    },
    // 批量改变规格价格
    changePrice (index, key) {
      // let reg = /^\d+(\.\d+)?$/
      // if (index === 3 && !reg.test(this.skuForm.min_selling_price)) {
      //   this.$message.error('请输入正确的价格！')
      //   return
      // }
      // if (index === 2 && !reg.test(this.skuForm.max_selling_price)) {
      //   this.$message.error('请输入正确的价格！')
      //   return
      // }
      this.sampleData.table.body.forEach(row => {
        this.setSkuTable(row, index, key)
      })
    },
    // 单个修改规格价格
    changeCostPrice (val, index, row) {
      let reg = /^\d+(\.\d+)?$/
      if (!reg.test(val)) {
        this.$message.error('请输入正确的数字！')
        this.vaild = true
      } else {
        this.vaild = false
      }
    },
    // 删除规格SKU
    deleteSku (item, index) {
      this.sampleData.table.body.splice(index, 1)
      if (this.sampleData.table.body.length) {
        let len = this.sampleData.table.header.length
        let defaultNum = 8
        let obj = {}
        this.sampleData.items.forEach((spec, specIndex) => {
          spec.values.forEach(row => {
            if (row.is_selected) obj[row.name] = specIndex
          })
        })
        // 思路： 规格中所有勾选中的规格项如果在sku表中对应位置的name不存在那么就取消勾中状态
        let newObj = {}
        this.sampleData.table.body.forEach(bodyItem => {
          let num = 0
          for (let key in obj) {
            if (!newObj[key]) newObj[key] = 0
            if (bodyItem[obj[key]] === key) newObj[key]++
          }
        })
        for (let newKey in newObj) {
          if (!newObj[newKey]) {
            let index = this.sampleData.items[obj[newKey]].values.findIndex(val => val.name === newKey)
            if (index >= 0) this.sampleData.items[obj[newKey]].values.splice(index, 1)
          }
        }
      } else {
        this.sampleData.items.forEach((spec) => {
          spec.values = []
        })
      }
    },
    setSkuTable (row, num, key) {
      this.$set(row, row.length - num, this.skuForm[key] ? this.skuForm[key] : row[row.length - num])
    },
    async updataTable (item, headerIndex, type) {
      let spec_arr = []
      this.skuForm = {
        unit: '',
        store_count: ''
      }
      // 遍历所有规格，规格属性选中后以规格项名为key规格属性为值的形式保存下来
      this.sampleData.items.forEach((items, itemsIndex) => {
        items.values.forEach(row => {
          if (row.is_selected) {
            if (!spec_arr[itemsIndex] || !spec_arr[itemsIndex].name) spec_arr[itemsIndex] = { name: items.name, values: [] }
            spec_arr[itemsIndex].values.push(row.name)
          }
        })
      })
      // 枚举选中规格
      let navbar  = []
      let arr = []
      spec_arr.forEach(spec => {
        navbar.push(spec.name)
        arr.push(spec.values)
      })
      // 如果为空清空sku
      if (!navbar.length) {
        this.sampleData.table = { header: [], body: [] }
        return
      }
      // 为sku表头追加默认数据
      let header = ['单位', '库存量']
      navbar = [...navbar, ...header]
      let result = await this.reduceMultipleArr(arr)
      let body = []
      result.forEach(item => {
        let row = item.split(/&#/)
        let prices = ['', '']
        row = [...row, ...prices]
        body.push(row)
      })
      if (type === 'new') {
        let newBody = []
        body.forEach(bodyItem => {
          if (bodyItem[headerIndex] === item.name) {
            newBody.push(bodyItem)
          }
        })
        this.sampleData.table = { header: navbar, body: [...this.sampleData.table.body, ...newBody] }
      } else {
        this.sampleData.table = { header: navbar, body: body }
      }
    },
    reduceMultipleArr (arr = []) {
      return arr.reduce((acc,currentItem)=>{
        return this.reduceTwoArr(acc,currentItem)
      })
    },
    reduceTwoArr (source1, source2) {
      let result = []
      source1.forEach(item => {
        source2.forEach(item2 => {
          result.push(`${item}&#${item2}`)
        })
      })
      return result
    },
    setUploadBtn () {
      if (this.sampleData.items.length) {
        this.sampleData.items.forEach(item => {
          if (item.values.length) {
            item.values.forEach(row => {
              if (row.image) item.showUploadBtn = true
              else item.showUploadBtn = false
            })
          }
        })
        let status = this.sampleData.items.every((item, index) => { return !item.showUploadBtn })
        if (status) this.sampleData.items[0].showUploadBtn = true
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.upload-body {
  padding: 0 32px 16px;
}
.upload-section-form {
  background: #fff;
}
.upload-section {
  width: 100%;
  margin-top: 20px;
  background: #fff;
  padding: 25px 0;
  border-radius: 4px;
  display: flex;
}
.upload-section-header {
  width: 250px;
  padding: 0 22px;
  .upload-section-title {
    padding: 10px 16.5px;
    border-radius: 0 50px 50px 0;
    background: #FF708B;
    font-size: 18px;
    line-height: 26px;
    color: #fff;
  }
}
.upload-section-content {
  flex: 1;
  padding: 0 22px;
}
.form-item {
  display: flex;
  align-items: center;
  margin-top: 15px;
  font-size: 12px;
  color: #333333;
  &.form-item-start {
    align-items: flex-start;
    .form-item-label {
      line-height: 60px;
    }
  }
  &.spec-sku {
    .form-item-label {
      line-height: 20px;
    }
  }
  &.form-item-top {
    align-items: flex-start;
  }
  & .form-item-body {
    display: flex;
    align-items: center;
    width: 1000px;
  }
  & .form-item-label {
    min-width: 130px;
    text-align: right;
    padding-right: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
    &.form-item-label_import {
      &:before {
        content: '*';
        color: #FF0000;
      }
    }
    &.form-item-label_strong {
      font-weight: 600;
      font-size: 14px;
    }
  }
  & .form-item-bd {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-left: 5px;
    min-width: 340px;
    & .el-checkbox-group {
      margin-right: 40px;
      & .el-checkbox {
        margin-right: 20px;
      }
    }
    & .form-item-bd_input {
      display: flex;
      min-width: 130px;
      margin-bottom: 6px;
      height: 40px;
      line-height: 40px;
      padding-left: 21px;
      align-items: center;
      & .el-input {
        width: 200px;
        margin-right: 10px;
      }
      & .form-item-bd_input-value {
        color: #0f73e6;
        cursor: pointer;
        text-decoration: underline;
      }
    }
  }
  & .form-item-bd_setting {
    display: flex;
    align-items: center;
    margin-left: 5px;
    margin-right: 10px;
    width: 150px;
    max-width: 150px;
  }
}
.form-item-edit {
  margin-left: 5px;
  color: #0f73e6;
  cursor: pointer;
  .iconfont {
    margin-right: 5px;
  }
}
.flex-center {
  display: flex;
  align-items: center;
  .el-button {
    margin-right: 15px;
  }
}
.form-item-input {
  .el-input {
    width: 500px;
  }
}
.form-item-ft-info {
  margin-left: 10px;
  font-size: 14px;
  color: #CCCCCC;
  line-height: 28px;
}
.form-item-spec {
  flex: 1;
}
.spec-table {
  margin-bottom: 20px;
}
.spec-table-header {
  width: 100%;
  height: 60px;
  padding: 0 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #FAFAFA;
  border: 1px solid #D9D9D9;
}
.spec-hd-value {
  display: flex;
  align-items: center;
  .spec-hd-value-label {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
  }
  .spec-hd-value-bd {
    width: 150px;
    margin-left: 20px;
  }
}
.spec-hd-handle {
  display: flex;
  align-items: center;
  cursor: pointer;
  .iconfont {
    font-size: 14px;
    background: #999999;
  }
  .spec-hd-handle-btn {
    margin-left: 10px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #666666;
    line-height: 20px;
    cursor: pointer;
  }
}
.spec-table-handle {
  margin-top: 20px;
  display: flex;
  align-items: center;
  .spec-table-handle-info {
    margin-left: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #CCCCCC;
    line-height: 20px;
  }
}
.spec-table-body {
  padding: 24px 46px;
  background: #FFFFFF;
  border: 1px solid #D9D9D9;
  border-top: none;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .spec-table-body-label {
    margin-right: 20px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
    flex-shrink: 0;
    margin-bottom: 10px;
  }
  .spec-table-body-value {
    display: flex;
    align-items: center;
    margin-right: 20px;
    margin-bottom: 10px;
    .spec-table-body-input {
      position: relative;
      width: 150px;
      & .iconfont {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        font-size: 16px;
        transform: translate(50%, -50%);
        z-index: 99;
        cursor: pointer;
      }
      &:hover {
        & .iconfont {
          display: inline-block;
        }
      }
    }
    &:hover {
      & .spec-item-ft {
        opacity: 1;
      }
    }
    & .spec-item-ft {
      display: flex;
      opacity: 0;
      align-items: center;
      padding-left: 10px;
      .iconfont {
        font-size: 20px;
        color: #999;
      }
    }
    .spec-table-body-img {
      position: relative;
      width: 28px;
      height: 28px;
      margin-left: 10px;
      background: #FFFFFF;
      border: 1px solid #DDDDDD;
      background-position: center;
      background-repeat: no-repeat;
      background-size: contain;
      .iconfont {
        position: absolute;
        top: 0;
        right: 0;
        font-size: 16px;
        transform: translate(50%, -50%);
      }
    }
    .spec-table-body-upload {
      position: relative;
      margin-left: 10px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 20px;
      cursor: pointer;
      & .el-input {
        width: 68px;
        height: 28px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        opacity: 0;
      }
    }
  }
  .spec-table-body-ft {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #0F73E6;
    line-height: 20px;
    cursor: pointer;
    margin-bottom: 10px;
  }
}
.spec-sku-table {
  flex: 1;
  .spec-sku-info {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 20px;
  }
}
.upload-form-bd-header {
  width: 100%;
  padding: 10px 20px;
  margin-bottom: 20px;
  background: #FAFAFA;
  display: flex;
  align-items: center;
}
.form-bd-title {
  font-size: 14px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #333333;
  line-height: 20px;
}
.model-body {
  max-height: 200px;
  overflow-y: auto;
  .model-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 10px;
  }
  .model-item-title {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
  }
  .model-item-handle {
    display: flex;
    align-items: center;
    .iconfont {
      margin-left: 10px;
    }
  }
  .model-item-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 20px;
  }
  .model-item {
    padding: 9px 20px;
    border-bottom: 1px solid #DDDDDD;
    cursor: pointer;
    &:hover {
      background: #F8F8F8;
      .model-item-setting {
        display: inline-block;
      }
      .model-item-time_handle {
        display: inline-block;
      }
    }
  }
  .model-item-default {
    font-size: 14px;
    color: #333333;
  }
  .model-item-setting {
    display: none;
    font-size: 14px;
    color: #0f73e6;
    cursor: pointer;
  }
  .model-item-time {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
    line-height: 20px;
    .model-item-time_bd {
      font-size: 14px;
      color: #999999;
    }
    .model-item-time_handle {
      display: none;
      font-size: 14px;
      color: #C2212A;
    }
  }
}
.form-bd-select {
  width: 150px;
  height: 28px;
  padding: 4px 10px;
  margin-left: 20px;
  background: #FFFFFF;
  border-radius: 2px;
  border: 1px solid #D9D9D9;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #333333;
  cursor: pointer;
  .form-bd-select-value {
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 20px;
    &.form-bd-select-value-placeholder {
      color: #ccc;
    }
  }
}
.form-bd-header-handle {
  display: flex;
  align-items: center;
  .form-bd-header-btn {
    padding: 5px 18px;
    margin-left: 20px;
    background: #ECECEC;
    border-radius: 2px;
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 18px;
    cursor: pointer;
  }
}
.table-list {
  & .table-tr {
    display: flex;
    & .table-td {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 44px;
      min-width: 100px;
      flex: 1;
      border: 1px solid #DDD;
      border-top: none;
      border-right: none;
      &:last-child {
        border-right: 1px solid #DDD;
      }
      & .table-td-body {
        text-align: center;
        &.table-td-input {
          width: 100px;
        }
      }
    }
  }
}
.form-item-draggable,
.form-item-draggable-transition {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.form-item-bd-info {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
  line-height: 20px;
}
.form-item-add {
  width: 110px;
  height: 110px;
  margin-right: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  &.form-item-add_upload {
    cursor: pointer;
    border: 1px dashed #999;
  }
  &.form-item-add_img {
    position: relative;
    background-position: center;
    background-repeat: no-repeat;
    background-size: contain;
    cursor: pointer;
    margin-bottom: 15px;
    & .el-checkbox-iconfont {
      position: absolute;
      right: -8px;
      top: -8px;
      font-size: 16px;
      display: none;
    }
    & .form-item-add_operation {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      width: 100%;
      height: 25px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0,0,0,0.50);
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #FFFFFF;
      line-height: 17px;
    }
    .form-item-add_tag {
      position: absolute;
      top: 0;
      left: 0;
      width: 45px;
      height: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0,0,0,0.50);
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #FFFFFF;
      line-height: 17px;
    }
  }
  & .el-icon-plus {
    display: block;
    font-size: 36px;
    color: #999
  }
  & .form-item-add_text {
    margin-top: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 20px;
  }
}
.detail-footer-imgs {
  padding: 30px 0 0;
  text-align: center;
}
.detail-footer-img {
  text-align: center;
}
.detail-footer-img img {
  height: 100%;
}
.content-footer {
  margin-top: 20px;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #ebeef5;
}
</style>